using System;
using System.Collections.Generic;
using System.Data;
using System.Web.SessionState;
using RoleDataTableAdapters;

/// <summary>
/// Summary description for UserManager
/// </summary>
public class UserManager
{
    public const string SessionName = "user";
    private static Dictionary<UserRoleEnum, List<int>> roles;

    static UserManager()
    {
        roles = new Dictionary<UserRoleEnum, List<int>>();

        RoleData.RoleDataTableDataTable roleTable = new RoleData.RoleDataTableDataTable();
        RoleDataAdapter roleDA = new RoleDataAdapter();
        roleDA.Fill(roleTable);

        addRole(UserRoleEnum.Admin, roleTable);
        addRole(UserRoleEnum.Default, roleTable);
        addRole(UserRoleEnum.Partner, roleTable);
        addRole(UserRoleEnum.Worker, roleTable);
        addRole(UserRoleEnum.All, roleTable);

        mergeRole(UserRoleEnum.Register, roles[UserRoleEnum.Worker]);
        mergeRole(UserRoleEnum.Register, roles[UserRoleEnum.Partner]);

        mergeRole(UserRoleEnum.Admin, roles[UserRoleEnum.Register]);
        mergeRole(UserRoleEnum.Admin, roles[UserRoleEnum.Default]);
    }

    private static void mergeRole(UserRoleEnum userRoleEnum, List<int> roleIds)
    {
        if (roleIds != null)
        {
            if (!roles.ContainsKey(userRoleEnum))
            {
                roles[userRoleEnum] = new List<int>();
            }

            roles[userRoleEnum].AddRange(roleIds);
        }
    }

    private static void addRole(UserRoleEnum roleCode, RoleData.RoleDataTableDataTable roleTable)
    {
        try
        {
            DataRow[] rows = roleTable.Select("code='" + roleCode + "'");
            if (rows != null && rows.Length > 0)
            {
                List<int> list = new List<int>();
                list.Add((int) rows[0][roleTable.idColumn]);
                roles.Add(roleCode, list);
            }
        }
        catch(Exception)
        {
            
        }
    }

    public UserManager()
    {
    }

    public static User GetCurrentUser(HttpSessionState session)
    {
        return (session[SessionName] as User) ?? DefaultUser.Instance;
    }

    public static List<int> GetRoleIds(UserRoleEnum userRole)
    {
        return roles[userRole];
    }

    public static UserRoleEnum GetRoleTypeId(int roleId)
    {
        if (roles[UserRoleEnum.Default][0] == roleId)
        {
            return UserRoleEnum.Default;            
        }
        if (roles[UserRoleEnum.Partner][0] == roleId)
        {
            return UserRoleEnum.Partner;
        }
        if (roles[UserRoleEnum.Worker][0] == roleId)
        {
            return UserRoleEnum.Worker;
        }

        return UserRoleEnum.Default;
    }

}